package com.gitee.sop.admin.service.serve;

import com.gitee.fastmybatis.core.PageInfo;
import com.gitee.fastmybatis.core.query.LambdaQuery;
import com.gitee.fastmybatis.core.support.LambdaService;
import com.gitee.sop.admin.common.enums.NotifyStatusEnum;
import com.gitee.sop.admin.common.exception.BizException;
import com.gitee.sop.admin.dao.entity.NotifyInfo;
import com.gitee.sop.admin.dao.mapper.NotifyInfoMapper;
import com.gitee.sop.notify.api.NotifyService;
import com.gitee.sop.notify.api.resp.NotifyResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;


/**
 * @author thc
 */
@Slf4j
@Service
public class NotifyInfoService implements LambdaService<NotifyInfo, NotifyInfoMapper> {

    @DubboReference
    private NotifyService notifyService;

    public PageInfo<NotifyInfo> doPage(LambdaQuery<NotifyInfo> query) {
        query.orderByDesc(NotifyInfo::getId);
        PageInfo<NotifyInfo> page = this.page(query);

        // 格式转换
        return page.convert(isvInfo -> {

            return isvInfo;
        });
    }

    public int push(Long id, String url) {
        if (StringUtils.isNotBlank(url)) {
            this.query()
                    .eq(NotifyInfo::getId, id)
                    .set(NotifyInfo::getNotifyUrl, url)
                    .update();
        }
        NotifyResponse notifyResponse = notifyService.notifyImmediately(id);
        log.info("重新推送结果, notifyResponse={}", notifyResponse);
        if (!notifyResponse.getSuccess()) {
            throw new BizException(notifyResponse.getMsg());
        }
        return 1;
    }

    public int end(Long id) {
        return this.query()
                .eq(NotifyInfo::getId, id)
                .eq(NotifyInfo::getNotifyStatus, NotifyStatusEnum.SEND_FAIL.getValue())
                .set(NotifyInfo::getNotifyStatus, NotifyStatusEnum.END.getValue())
                .update();
    }
}
